﻿using JiveMessenger.Utilities;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace JiveMessenger.ImagePreview.Imgur
{
    internal static class ImgurManager
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        internal static ImgurVideoFormat ImgurVideoFormat { get; set; }
        internal static bool EnableImgurVideo { get; set; }

        internal const string ImgurAppKey = "54b70a84c0b2110";
        internal static string GetImgurLink(string id, bool getThumbnail, string extension = "")
        {
            if (string.IsNullOrEmpty(extension))
                extension = ".jpg";

            if (getThumbnail)
                return String.Format("http://i.imgur.com/{0}h{1}", id, extension);
            else
                return String.Format("http://i.imgur.com/{0}{1}", id, extension);
        }
        internal static ImgurLink GetImgurId(string url)
        {
            if (String.IsNullOrEmpty(url))
                return null;

            Regex imgurRegex = new Regex(@"imgur\.com(?:\/(a|gallery|signin))?\/([^\W_]{5,7})(?:\/|\.[a-zA-Z]+|#([^\W_]{5,7}|\d+))?");
            Match imgurMatch = imgurRegex.Match(url);
            if (imgurMatch.Success && !string.IsNullOrEmpty(imgurMatch.Groups[2].Value))
            {

                var view = imgurMatch.Groups[1].Value;
                var id = imgurMatch.Groups[2].Value;
                switch (view)
                {
                    case "signin":
                        return null;
                    case "a": // album view:
                        return new ImgurLink(ImgurLinkType.Album, id);
                    case "gallery":
                        return new ImgurLink(ImgurLinkType.Gallery, id);
                    default:
                        {
                            string ext = VirtualPathUtility.GetExtension(url);
                            if (String.IsNullOrEmpty(ext))
                                return new ImgurLink(ImgurLinkType.WrappedImage, id);
                            else
                                return new ImgurLink(ImgurLinkType.Image, id);
                        }
                }
            }

            return null;
        }

        internal static ImgurInfo GetImgurInfoForUrl(string url)
        {
            ObjectCache cache = MemoryCache.Default;
            ImgurInfo info = cache.FirstOrDefault(x =>
            {
                if (x.Key == "ImgurInfo-" + url)
                    return true;
                else if (x.Value is ImgurInfo)
                {
                    ImgurInfo imgInfo = (ImgurInfo)x.Value;
                    if (imgInfo.data.images != null && imgInfo.data.images.Any(i => i.link == url))
                        return true;
                    else if (imgInfo.data.link == url)
                        return true;
                }


                return false;
            }).Value as ImgurInfo;

            return info;
        }

        internal static ImgurInfo DownloadImgurInfo(string downloadUrl)
        {
            ImgurInfo info = null;
            TimeoutWebClient wc = new TimeoutWebClient(3000)
            {
                Proxy = null,
                Encoding = Encoding.UTF8
            };
            wc.Headers.Add("Authorization", string.Format("Client-ID {0}", ImgurAppKey));
            try
            {
                string v = wc.DownloadString(downloadUrl);
                if (!String.IsNullOrEmpty(v))
                {
                    info = JsonConvert.DeserializeObject<ImgurInfo>(v);
                }

            }
            catch (System.Net.WebException ex)
            {
                Logger.ErrorException("Error downloading info from imgur", ex);
            }
            return info;
        }

        internal static string GetImageTitle(ImgurData item)
        {
            string title = item.title;
            if (!String.IsNullOrEmpty(item.description))
            {
                if (!string.IsNullOrEmpty(title))
                    title += Environment.NewLine + Environment.NewLine;
                title += item.description;
            }
            return title;
        }
        internal static string GetImageTitle(ImgurImage item)
        {
            string title = item.title;
            if (!String.IsNullOrEmpty(item.description))
            {
                if (!string.IsNullOrEmpty(title))
                    title += Environment.NewLine + Environment.NewLine;
                title += item.description;
            }
            return title;
        }
        internal static string GetVideoUrlForImgurItem(ImgurData item)
        {
            switch (ImgurVideoFormat)
            {
                default:
                case ImgurVideoFormat.mp4:
                    return item.mp4;
                case ImgurVideoFormat.WebM:
                    return item.webm;
            }
        }
        internal static string GetVideoUrlForImgurItem(ImgurImage item)
        {
            switch (ImgurVideoFormat)
            {
                default:
                case ImgurVideoFormat.mp4:
                    return item.mp4;
                case ImgurVideoFormat.WebM:
                    return item.webm;
            }
        }
    }
}
